<?php

/*
    Analytics API Example
    
    A simple script demonstrating usage of the GreqoAnalyticsApi class with
    the Google Analytics Data API.
    
    Update the settings section with values for your Google account.
    
    Warning: if you have many accounts this may take a while.  Alternately, you
    can manually set the profile list.
*/

// SETTINGS (edit these)
$google_email = 'TBA';
$google_pw    = 'TBA';

// import classes to test
$root_dir = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR;
require_once($root_dir . 'greqo/analytics_api.class.php');

// authenticate
$Greqo = new GreqoAnalyticsApi(1);
$Greqo->service = 'analytics';
$Greqo->email = $google_email;
$Greqo->password = $google_pw;
if ( !$Greqo->request_clientlogin_token() ) die('update script settings');

// get account profile list
$AccountList = $Greqo->get_account_list();
foreach ( $AccountList as $Profile )
    $ProfileList[$Profile['title']] = $Profile['ga:profileId'];

// get report data list
$ReportList = array();
foreach ( $ProfileList as $title => $pid ) {
    $ReportData[$title] = $Greqo->get_current_visitor_report($pid);
    $SortList[$title] = $ReportData[$title]['aggregate']['ga:visitors'];
}
arsort($SortList);
$DayList = array_keys($ReportData[$title]['detail']);

// debug
#$Greqo->pr(sprintf('total visitors: %s', array_sum(array_values($SortList))));
#$Greqo->pr($ReportData[$title]);
#$Greqo->pr($SortList);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<head>
    <title>Greqo Google Analytics API Example</title>
    <style>
        body { font-family:arial,sans-serif; font-size:12px; }
        table td { padding:4px; background-color:#eeeeff; }
    </style>
</head>

<body>
    <h1>Greqo Google Analytics API Example</h1>
<table>
    <tr>
        <th></th><th colspan=3>yesterday</th><th colspan=3>today</th>
    </tr>
    <tr>
        <th>site</th><th>visitors</th><th>visits</th><th>views</th>
        <th>visitors</th><th>visits</th><th>views</th>
    </tr>
    <?php foreach ( $SortList as $title => $visitor_count ): ?>
        <?php $R = $ReportData[$title]; ?>
        <?php printf('<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>',
                      $title,
                      $R['detail'][$DayList[0]]['ga:visitors'],
                      $R['detail'][$DayList[0]]['ga:visits'],
                      $R['detail'][$DayList[0]]['ga:pageviews'],
                      $R['detail'][$DayList[1]]['ga:visitors'],
                      $R['detail'][$DayList[1]]['ga:visits'],
                      $R['detail'][$DayList[1]]['ga:pageviews']
                    ); ?>
    <?php endforeach; ?>
</table>
</body>
</html>

